package homework.hw3;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/22 8:50
 * 通过servlet完成将图片展示在页面上
 **/
@WebServlet("/beauty")
public class Beauty extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.获取请求参数（filename），得知要展示的图片名
         * 2.根据图片名获得图片存放的真实路径
         * 3.通过输入流读取图片
         * 4。通过输出流将图片展示在页面上*/
        String filename = req.getParameter("filename");
        System.out.println(filename);
        /*获取图片的真实路径
        * 通过ServletContext对象（代表整个web应用）*/
        ServletContext servletContext = req.getServletContext();
        String realPath = req.getServletContext().getRealPath("/img/"+filename);
        System.out.println(realPath);
        /*通过字节输入流读取文件，响应的字节输出流写数据到页面*/
        FileInputStream fis=new FileInputStream(realPath);
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] bytes=new byte[1024*2];
        int len=0;
        //如果没有读取到文件末尾（-1）就一直读取
        while ((len=fis.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
